package com.mai.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;

import com.mai.realtime.app.BaseAppV1;
import com.mai.realtime.bean.QuestionCreateBean;
import com.mai.realtime.common.Constant;
import com.mai.realtime.util.AtguiguUtil;
import com.mai.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.HashSet;


public class Dws_QuestionCreateStatusAggWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_QuestionCreateStatusAggWindow().init(
                4207,
                2,
                "Dws_QuestionCreateStatusAggWindow6",
                Constant.TOPIC_DWD_PAPER_QUESTION
        );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {

        // 封装到bean
        SingleOutputStreamOperator<QuestionCreateBean> beanStream = findUs(stream);


        // 1. 开窗聚合
        SingleOutputStreamOperator<QuestionCreateBean> resultStream = windowAndAgg(beanStream);

        resultStream.print();
        // 3. 写出
        writeToDoris(resultStream);
    }

    private void writeToDoris(SingleOutputStreamOperator<QuestionCreateBean> resultStream) {
        resultStream
                .map(bean -> {
                    SerializeConfig config = new SerializeConfig();
                    config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;  // 转成json的时候, 属性名使用下划线
                    return JSON.toJSONString(bean, config);
                })
                .addSink(FlinkSinkUtil.getDorisSink("gmall.dws_question_create_status_agg_window"));
    }





    private SingleOutputStreamOperator<QuestionCreateBean> windowAndAgg(
            SingleOutputStreamOperator<QuestionCreateBean> beanStream) {
        return beanStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<QuestionCreateBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((bean, ts) -> bean.getTs())
                )
                .keyBy(obj ->obj.getQuestionId())
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .reduce(
                        new ReduceFunction<QuestionCreateBean>() {
                            @Override
                            public QuestionCreateBean reduce(QuestionCreateBean bean1,
                                                             QuestionCreateBean bean2) throws Exception {
                                bean1.setStuCt(bean1.getStuCt() + bean2.getStuCt());
                                bean1.setCorrectStuCt(bean1.getCorrectStuCt() + bean2.getCorrectStuCt());


                                return bean1;
                            }
                        },
                        new ProcessWindowFunction<QuestionCreateBean, QuestionCreateBean, String, TimeWindow>() {
                            @Override
                            public void process(String key,
                                                Context ctx,
                                                Iterable<QuestionCreateBean> elements,
                                                Collector<QuestionCreateBean> out) throws Exception {

                                QuestionCreateBean bean = elements.iterator().next();

                                bean.setStt(AtguiguUtil.toDateTime(ctx.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDateTime(ctx.window().getEnd()));

                                bean.setCurDate(AtguiguUtil.toDate(System.currentTimeMillis()));

                                out.collect(bean);
                            }
                        }


                );
    }

    private SingleOutputStreamOperator<QuestionCreateBean> findUs(DataStreamSource<String> stream) {
        return stream
                .map(JSON::parseObject)
                .keyBy(obj -> obj.getString("question_id")+obj.getString("user_id"))
                .process(new KeyedProcessFunction<String, JSONObject, QuestionCreateBean>() {

                    private ValueState<String> dailyState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        dailyState = getRuntimeContext().getState(new ValueStateDescriptor<String>("dailyState", String.class));

                    }

                    @Override
                    public void processElement(JSONObject obj,
                                               Context ctx,
                                               Collector<QuestionCreateBean> out) throws Exception {

                        Long ts = obj.getLong("ts")*1000;
                        String question_id = obj.getString("question_id");


                        Long StuCt = 0L;
                        Long CorrectStuCt = 0L;

                        HashSet<String> set = new HashSet<>();


                        String today = AtguiguUtil.toDate(ts);
                        //如果状态
                        if (today.equals(dailyState.value()) ) {
                            StuCt++;
                            CorrectStuCt = Long.parseLong(obj.getString("is_correct"));
                        }else if(dailyState == null){
                            StuCt = 1L;
                            CorrectStuCt = Long.parseLong(obj.getString("is_correct"));
                            dailyState.update(today);
                        }else {
                            StuCt = 0L;
                            dailyState.update(today);
                        }

                        out.collect(new QuestionCreateBean("", "",
                                "",
                                question_id,
                                StuCt,
                                CorrectStuCt,
                                ts
                        ));
                    }
                });

    }
}
